using InputSimulatorPro;
using InputSimulatorPro.Resources.Natives;
using JiJiDownApp.Lib;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows;
using Microsoft.Win32;
using YamlDotNet.Serialization;

namespace JiJiDownApp
{
    public partial class MainWindow : Window
    {
        private Process? _externalProcess;
        private DateTime _consoleOutputChangeTime;
        private JijiDownConfig? _jijiDownConfig = null;

        private static string? _jiJiDownCoreExePath = string.Empty;
        private static string _jijiDownConfigFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"jijidown\config.yaml");

        public AppConfig AppConfig { get; set; } = new AppConfig(_jiJiDownCoreExePath, _jijiDownConfigFilePath);
        // jijiDown配置
        public JijiDownConfig JijiConfig
        {
            get
            {
                if (_jijiDownConfig == null)
                {
                    _jijiDownConfig = new JijiDownConfig();

                    if (File.Exists(_jijiDownConfigFilePath))
                    {
                        string yamlContent = File.ReadAllText(_jijiDownConfigFilePath);

                        // 配置反序列化器（可选：处理命名风格，如驼峰式）
                        var deserializer = new DeserializerBuilder()
                            //.WithNamingConvention(CamelCaseNamingConvention.Instance)
                            .IgnoreUnmatchedProperties()
                            .Build();

                        // 将 YAML 转为对象
                        JijiDownConfig config = deserializer.Deserialize<JijiDownConfig>(yamlContent);
                        _jijiDownConfig = config;
                    }

                    if (string.IsNullOrEmpty(_jijiDownConfig.DownloadTask.TempDir))
                    {
                        _jijiDownConfig.DownloadTask.TempDir = Path.Combine(Path.GetTempPath(), "JiJiDown");
                    }
                }
                return _jijiDownConfig;
            }
        }

        public string TempDir => JijiConfig.DownloadTask.TempDir ?? Path.Combine(Path.GetTempPath(), "JiJiDown");


        public string? DownloadDir => JijiConfig.DownloadTask.DownloadDir??null;


#pragma warning disable CS8618 // 在退出构造函数时，不可为 null 的字段必须包含非 null 值。请考虑声明为可以为 null。
        public MainWindow()
        {
            InitializeComponent();

            // 窗口居中
            WindowStartupLocation = WindowStartupLocation.CenterScreen;

            if (!CheckAppConfig())
            {
                Close();
                return;
            }

            BindingButtonsClickEvent();
            //Closing += MainWindow_Closing;


            Browser.CoreWebView2InitializationCompleted += (sender, e) =>
            {
                //移除元素
                //Browser.CoreWebView2.DOMContentLoaded +=  (sender, e) =>
                //{
                //    Thread.Sleep(200);
                //    //Browser.CoreWebView2.ExecuteScriptAsync($"alert('hhhh')");
                //     Browser.CoreWebView2.ExecuteScriptAsync($"document.getElementsByClassName('css-4rwrqm')[0].removeChild(document.getElementsByClassName('css-g99pjq')[0])");

                //    //Browser.CoreWebView2.ExecuteScriptAsync($"document.onload = function () {{ alert('Hello World!')}};");


                //};

                Browser.CoreWebView2.NavigationCompleted += async (o, ev) =>
                {
                    if (ev.IsSuccess)
                    {
                        //Browser.CoreWebView2.ExecuteScriptAsync($"alert('hhhh')");
                        Thread.Sleep(200);
                        await Browser.CoreWebView2.ExecuteScriptAsync(@"document.getElementsByClassName('css-4rwrqm')[0].removeChild(document.getElementsByClassName('css-g99pjq')[0])");

                    }
                };

                Browser.CoreWebView2.Navigate("https://beta.sabe.cc/");
            };

            // 加载网页
            //Browser.Source = new Uri("https://beta.sabe.cc/");
            Browser.EnsureCoreWebView2Async(null);


            // 启动外部应用
            RunExternalApp();



            //// 异步启动日志任务
            //_ = logStartAsync();

        }

        private bool CheckAppConfig()
        {
            
            if (File.Exists(AppConfig.AppConfigPath))
            {
                var deSerializer = new DeserializerBuilder().IgnoreUnmatchedProperties().Build();
                var f = File.ReadAllText(AppConfig.AppConfigPath);
                AppConfig = deSerializer.Deserialize<AppConfig>(f);
                _jiJiDownCoreExePath       = AppConfig.JiJiDownCoreExePath;
                _jijiDownConfigFilePath = AppConfig.JijiDownConfigFilePath;
            }
            else
            {
                if (!WriteAppConfig())
                {
                    return false;
                }
            }

            if (!File.Exists(AppConfig.JijiDownConfigFilePath))
            {
                MessageBox.Show($"未找到JiJiDown配置文件：{AppConfig.JijiDownConfigFilePath}，请确认文件是否存在。","提示", MessageBoxButton.OK,icon:MessageBoxImage.Warning);
                return false;

            }

            return true;
        }

        private bool WriteAppConfig()
        {
            if (AppConfig.JiJiDownCoreExePath.IsNullOrEmpty())
            {
                var dialog = new OpenFileDialog
                {
                    Title = "请选择JiJiDownCore-win64.exe文件",
                    ShowReadOnly = true,
                    Multiselect = false,
                    Filter = "JiJiDownCore执行文件|JiJiDownCore-win64.exe"
                };
                if (dialog.ShowDialog().GetValueOrDefault())
                {
                    AppConfig.JiJiDownCoreExePath = dialog.FileName;
                }
                else
                {
                    this.Close();
                    return false;
                }
            }

            File.Create(AppConfig.AppConfigPath).Close();
            var serializer = new SerializerBuilder().Build();
            var yamlContent = serializer.Serialize(AppConfig);
            File.WriteAllText(AppConfig.AppConfigPath, yamlContent);
            return true;
        }

        private void BindingButtonsClickEvent()
        {
            // 搜索
            SearchButton.Click += (sender, e) =>
            {

                Browser.Focus();
                VirtualKeyShort[] keys = { VirtualKeyShort.CONTROL, VirtualKeyShort.KEY_F };
                InputSimulator.Keyboard.SimultaneousKeyPress(keys);

            };
            ClearButton.Click += (sender, e) => ConsoleOutput.Clear();

            // 删除缓存文件夹
            ClearCacheButton.Click += (sender, e) =>
            {

                var dialogResult = MessageBox.Show($"确定删除缓存文件夹{TempDir}吗？", "警告", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                if (dialogResult == MessageBoxResult.OK)
                {
                    try
                    {
                        //Directory.Delete(TempDir, true);
                        //Directory.CreateDirectory(TempDir);
                        DeleteTempFile();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }

            };

            // 打开缓存文件夹
            OpenCacheButton.Click += (sender, e) =>
            {
                if (Directory.Exists(TempDir))
                {
                    //Process.Start("explorer.exe", TempDir);
                    OpenerFolder.OpenFolderCmd(TempDir);
                }
            };

            // 打开配置文件夹
            OpenConfigButton.Click += (sender, e) =>
            {
                if (Directory.Exists(AppConfig.JijiDownConfigDir))
                {
                    OpenerFolder.OpenFolderCmd(AppConfig.JijiDownConfigDir);
                }
                else
                {
                    MessageBox.Show($"配置文件夹{AppConfig.JijiDownConfigDir}不存在！");
                }

            };

            // 打开下载文件夹
            OpenDownLoadButton.Click += (sender, e) =>
            {
                if (Directory.Exists(DownloadDir))
                {
                    OpenerFolder.OpenFolderCmd(DownloadDir);
                }
                else
                {
                    MessageBox.Show($"下载文件夹{DownloadDir}不存在");
                }

            };

            EditConfigButton.Click += (sender, e) =>
            {
                Process.Start("notepad", _jijiDownConfigFilePath);
            };

            // 重启服务
            RestartServiceButton.Click += (sender, e) =>
            {
                _externalProcess?.Kill();
                _externalProcess?.WaitForExit();
                RunExternalApp();
                Thread.Sleep(1000);
                Browser.CoreWebView2.Reload();
                _jijiDownConfig = null;
            };

            // 退出
            ExitButton.Click += (sender, e) => Close();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            if (_externalProcess == null)
            {
                return;
            }

            //Thread.Sleep(500);
            if ((DateTime.Now - _consoleOutputChangeTime).TotalSeconds < 1)
            {
                if (MessageBox.Show("正在下载中，是否退出", "提示", button: MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            //Browser.Dispose();
            if (_externalProcess==null)
            {
                return;
            }
            try
            {
                _externalProcess?.Kill();
                //if (Directory.Exists(TempDir)){
                //    Directory.Delete(TempDir, true);
                //}
                //Directory.CreateDirectory(TempDir);
                _externalProcess?.WaitForExit();

                var processes = Process.GetProcessesByName("FFmpeg");
                if (processes.Length > 0)
                {
                    if (MessageBox.Show("是否终止FFmpeg转换进程？", "提示", button: MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        foreach (var p in processes)
                        {
                            p.Kill();
                            p.WaitForExit();
                        }
                    }
                }
                DeleteTempFile();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void RunExternalApp()
        {
            if (AppConfig.JiJiDownCoreExePath.IsNullOrEmpty())
            {
                if (!WriteAppConfig())
                {
                    return;
                }
            }

            try
            {
                string processName = "JiJiDownCore-win64";
                var process = Process.GetProcessesByName(processName);
                bool isRunning = process.Length > 0;
                if (isRunning)
                {
                    process[0].Kill();
                    process[0].WaitForExit();
                }

                
                _externalProcess = new Process();
                //_externalProcess.StartInfo.FileName = @"X:\Program Files\JiJiDown\resources\JiJiDownCore-win64.exe";
                _externalProcess.StartInfo.FileName               = AppConfig.JiJiDownCoreExePath;
                _externalProcess.StartInfo.Arguments              = "-debug";
                _externalProcess.StartInfo.WorkingDirectory       = @"X:\Program Files\JiJiDown\resources";
                _externalProcess.StartInfo.UseShellExecute        = false;
                _externalProcess.StartInfo.RedirectStandardOutput = true;
                _externalProcess.StartInfo.RedirectStandardError  = true;
                _externalProcess.StartInfo.CreateNoWindow         = true;
                // 禁用输出缓冲
                _externalProcess.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
                _externalProcess.StartInfo.StandardErrorEncoding = System.Text.Encoding.UTF8;

                _externalProcess.OutputDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                        AppendText(e.Data + Environment.NewLine);
                };
                _externalProcess.ErrorDataReceived += (sender, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                        AppendText($"[ERROR] {e.Data} \n");
                };

                var s = _externalProcess.Start();

                // 开始异步读取输出
                _externalProcess.BeginOutputReadLine();
                _externalProcess.BeginErrorReadLine();

                ConsoleOutput.AppendText(string.Format("已启动外部程序:{0}\n", _externalProcess.ToString()));
               
            }
            catch (Exception ex)
            {
                ConsoleOutput.AppendText($"操作失败: {ex.Message}\n");
            }
        }

        private void AppendText(string text)
        {
            Dispatcher.Invoke(() =>
            {
                if (!string.IsNullOrEmpty(text))
                    ConsoleOutput.AppendText(text);
                _consoleOutputChangeTime = DateTime.Now;
                ConsoleOutput.ScrollToEnd();
            });
        }

        private void DeleteTempFile()
        {
            foreach (var file in Directory.GetFiles(TempDir))
            {
                try
                {
                    File.Delete(file);
                }
                catch (Exception ex)
                {
                    ConsoleOutput.AppendText(ex.Message);
                }
            }
        }        
    }
}